package servlets;
/*
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import webmanager.model.Career;
import webmanager.model.Comment;
import webmanager.model.Subject;
import webmanager.model.User;
import webmanager.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ControllerServlet extends BaseController {

    public static final int ACTION_DEFAULT = 0;
    public static final int ACTION_VER_MATERIA = 1;
    public static final int ACTION_VER_CARRERA = 2;
    public static final int ACTION_VER_ANIO = 3;
    public static final int ACTION_VIEW_FILE = 12;
    public static final int ACTION_LOGOUT = 6;
    public static final int ACTION_REG_USR = 8;
    public static final int ACTION_SAVE_COMMENT = 9;
    public static final int ACTION_SHOW_MI_CUENTA = 10;
    public static final int ACTION_EDIT_USER = 11;

    protected static final String CARRERA_DEFAULT = "fi.inf";
    protected static final int ANIO_DEFAULT = 1;
    public static final String path = "/home/guest/Desktop/Info 2005/JsTps/Lab1/webManager/resources/files/";

    public static final int ACTION_LOAD_REG_USR_PAGE = 17;
    public static final int ACTION_CHANGE_SUBJECTS = 18;
    public static final int ACTION_UPLOAD = 19;
    public static final int ACTION_UPLOAD_FILE = 20;
    public static final int ACTION_DOWNLOAD_FILE = 21;
    public static final int ACTION_SEARCH_SUBJECT = 22;


    protected String handleAction(int actionId, HttpServletRequest request, HttpServletResponse response)
            throws Exception {//ServletException, IOException {

        String forwardUrl = "../jsp/error.jsp";

        String userName;
        String careerId;
        String comment;
        String password;
        List subjects;
        List types;
        List careers;
        int idSubject;
        Career career;


        switch (actionId) {
            case ACTION_DEFAULT:
                careers = CareerManager.getAlCareers();
                request.setAttribute("careers", careers);

                forwardUrl = "../jsp/welcome.jsp";
                break;
            case ACTION_VER_MATERIA:
                idSubject = Integer.parseInt(request.getParameter("idSubject"));

                Subject subject = SubjectManager.getSubject(idSubject);
                request.setAttribute("subject", subject);

                List priPar = FileManager.getSubjectFiles(idSubject, webmanager.model.File.PRIMER_PARCIAL);
                request.setAttribute("primerosParciales", priPar);
                List segPriPar = FileManager.getSubjectFiles(idSubject, webmanager.model.File.SEGUNDO_PARCIAL);
                request.setAttribute("segundosParciales", segPriPar);
                List recPriPar = FileManager.getSubjectFiles(idSubject, webmanager.model.File.REC_PRIMER_PARCIAL);
                request.setAttribute("recPrimerosParciales", recPriPar);
                List recSegPar = FileManager.getSubjectFiles(idSubject, webmanager.model.File.REC_SEGUNDO_PARCIAL);
                request.setAttribute("recSegundosParciales", recSegPar);
                List finales = FileManager.getSubjectFiles(idSubject, webmanager.model.File.FINAL);
                request.setAttribute("finales", finales);
                List apuntes = FileManager.getSubjectFiles(idSubject, webmanager.model.File.APUNTES);
                request.setAttribute("apuntes", apuntes);
                List resumen = FileManager.getSubjectFiles(idSubject, webmanager.model.File.RESUMEN);
                request.setAttribute("resumenes", resumen);
                List commentsSubject = CommentManager.getComments(idSubject, 0);
                request.setAttribute("subjectComments", commentsSubject);


                forwardUrl = "../jsp/niceViewSubject.jsp";
                break;

            case ACTION_CHANGE_SUBJECTS:
                // Cuando el flaco cambia la carrera en el Upload generico, recargamos desde aca
                types = webmanager.model.File.getTypes();
                request.setAttribute("types", types);
                careers = CareerManager.getAlCareers();
                request.setAttribute("careers", careers);
                int index = Integer.parseInt(request.getParameter("careersCombo"));
                careerId = ((Career) careers.get(index)).getIdCareer();
                subjects = PlanManager.getSubjectsInCareer(careerId);
                request.setAttribute("subjects", subjects);
                request.setAttribute("index", index);
                request.setAttribute("idSubject", -1);

                forwardUrl = "../jsp/upload.jsp";
                break;
            case ACTION_UPLOAD: // Este caso es cuando entran a subir sin venir de una materia especifica
                types = webmanager.model.File.getTypes();
                request.setAttribute("idSubject", request.getParameter("idSubject"));
                request.setAttribute("types", types);
                careers = CareerManager.getAlCareers();
                request.setAttribute("careers", careers);
                subjects = PlanManager.getSubjectsInCareer(CARRERA_DEFAULT);
                request.setAttribute("subjects", subjects);
                request.setAttribute("index", 0);
                request.setAttribute("subjectName", request.getParameter("subjectName"));

                forwardUrl = "../jsp/upload.jsp";

                break;
            case ACTION_UPLOAD_FILE: // Carga el archivo que me pasaron


                FileItemFactory factory = new DiskFileItemFactory();

                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(factory);
                final List items = upload.parseRequest(request);

                //Form Params
                Map<String, String> params = getParams(items);

                idSubject = Integer.parseInt(params.get("idSubject"));
                final int typeId = Integer.parseInt(params.get("typesCombo"));
                final String userFilename = params.get("fileName");

                //Uploaded Files
                Map<String, FileItem> files = getFiles(items);
                File uploadFile = uploadFile(files.get("uploadFile"));

                //if (items.get(0) == null) {// para evitar que inventen un path
                //y guardar un archivo mentiroso
                copy(uploadFile, new File(path + uploadFile.getName()));
                userName = getPrincipal(request).getName();
                int type = UserManager.getUser(userName).getType();
                boolean authorized = (type == User.MOD_TYPE || type == User.PROF_TYPE) ? true : false;
                webmanager.model.File wf = new webmanager.model.File(idSubject, "files/" + uploadFile.getName(), userName, userFilename, authorized, typeId);
                FileManager.saveFile(wf);

                //}

                //todo enviador de mails      no funca en fuckultad
                //EMail eMail = new EMail(UserManager.getAdmins(), "Archivo Pendiente", MailManager.getBodyPendientes(userName,userFilename,wf.getUrl()));
                //MailManager.sendMail(eMail);

                request.setAttribute("statusMessage", "Archivo subido");
                forwardUrl = "/servlet/controllerServlet?actionId=" + ControllerServlet.ACTION_VER_MATERIA + "&idSubject=" + idSubject;

                break;

            case ACTION_VER_CARRERA:
                careerId = request.getParameter("careerId");
                final String carreraC = careerId != null ? careerId : CARRERA_DEFAULT;
                subjects = PlanManager.getSubjectsInCareer(carreraC);
                career = CareerManager.getCareer(carreraC);
                request.setAttribute("career", career);
                request.setAttribute("subjectsInCareer", subjects);
                forwardUrl = "../jsp/viewCareer.jsp";
                break;
            case ACTION_VER_ANIO:
                careerId = request.getParameter("careerId");
                final String carrera = careerId != null ? careerId : CARRERA_DEFAULT;

                int year = careerId != null ? Integer.parseInt(request.getParameter("year")) : ANIO_DEFAULT;
                subjects = PlanManager.getSubjectsInYear(carrera, year);

                career = CareerManager.getCareer(carrera);
                request.setAttribute("career", career);
                request.setAttribute("subjectsInYear", subjects);
                forwardUrl = "../jsp/viewYear.jsp";
                break;


            case ACTION_LOGOUT:
                request.getSession().invalidate();
                request.setAttribute("statusMessage", "chau mostro!");
                forwardUrl = "../jsp/welcome.jsp";
                // Volvemos a cargar la carrera en la sesion que se crea sola
                careers = CareerManager.getAlCareers();
                request.setAttribute("careers", careers);
                break;

            case ACTION_REG_USR:
                userName = request.getParameter("newName");
                password = request.getParameter("newPass");
                String email = request.getParameter("newEmail");
                careerId = request.getParameter("careersCombo");
                year = Integer.parseInt(request.getParameter("year"));
                User rUser = new User(userName, password, careerId, year, email, User.USER_TYPE);
                boolean exists = UserManager.existsUser(userName);
                if (!exists) {
                    UserManager.register(rUser);
                    careers = CareerManager.getAlCareers();
                    request.setAttribute("careers", careers);
                    request.setAttribute("statusMessage", "Usuario registrado ;)");
                    forwardUrl = "../jsp/welcome.jsp";
                } else {
                    request.setAttribute("statusMessage", "nombre de usuario ya existente");
                    forwardUrl = "../jsp/register.jsp";
                }

                break;

            case ACTION_SAVE_COMMENT:
                comment = request.getParameter("contentArea");
                idSubject = Integer.parseInt(request.getParameter("idContainer"));
                type = Integer.parseInt(request.getParameter("commentType"));
                Comment comentario = new Comment(type, idSubject, comment, getPrincipal(request).getName());
                CommentManager.saveComment(comentario);
                if (comentario.getIsFile() == 0) {
                    forwardUrl = "/servlet/controllerServlet?actionId=" + ControllerServlet.ACTION_VER_MATERIA + "&idSubject=" + comentario.getIdContainer();
                } else {
                    forwardUrl = "/servlet/controllerServlet?actionId=" + ControllerServlet.ACTION_VIEW_FILE + "&idFile=" + comentario.getIdContainer();
                }
                request.setAttribute("statusMessage", "Comentario guardado");
                break;

            case ACTION_SHOW_MI_CUENTA:
                userName = getPrincipal(request).getName();
                User user = UserManager.getUser(userName);
                request.setAttribute("user", user);
                forwardUrl = "../jsp/showOptions.jsp";
                break;

            case ACTION_EDIT_USER:
                userName = getPrincipal(request).getName();
                user = UserManager.getUser(userName);
                password = request.getParameter("password");
                String newPassword = request.getParameter("nPassword");
                String newCPassword = request.getParameter("cPassword");

                if (password.equals(user.getPassword())) {
                    if (newPassword.equals(newCPassword)) {
                        user.setPassword(newPassword);
                        UserManager.update(user);
                        request.setAttribute("statusMessage", "Usuario actualizado");
                    } else {
                        request.setAttribute("statusMessage", "Wrong confirm password");
                    }
                } else {
                    request.setAttribute("statusMessage", "Wrong password");
                }
                request.setAttribute("user", user);
                forwardUrl = "../jsp/showOptions.jsp";
                break;


            case ACTION_VIEW_FILE:
                int idFile = Integer.parseInt(request.getParameter("idFile"));
                webmanager.model.File file = FileManager.getFile(idFile);
                if (file.getAuthorized()) {
                    request.setAttribute("file", file);
                    List commentsFile = CommentManager.getComments(idFile, 1);
                    request.setAttribute("fileComments", commentsFile);
                    request.setAttribute("typeName", file.getTypeName());
                    forwardUrl = "../jsp/niceViewFile.jsp";
                } else {
                    forwardUrl = "../jsp/fileNotAuthorized.jsp";
                }

                break;


            case ACTION_LOAD_REG_USR_PAGE:
                careers = CareerManager.getAlCareers();
                request.setAttribute("careers", careers);
                request.setAttribute("years", 5);
                forwardUrl = "../jsp/register.jsp";
                break;

            case ACTION_DOWNLOAD_FILE:
                idFile = Integer.parseInt(request.getParameter("idFile"));
                file = FileManager.getFile(idFile);
                if (file.getAuthorized()) {
                    file.incDownloads();
                    FileManager.update(file);


                    String filename = getServletContext().getRealPath(file.getUrl());
                    // Set the headers.
                    response.setContentType("application/x-download");
                    response.setHeader("Content-Disposition", "attachment; filename=" + file.getFileName());

                    // Send the file.
                    OutputStream out = response.getOutputStream();
                    returnFile(filename, out);  // Shown earlier in the chapter


                    return null;


                    //forwardUrl = "../" + file.getUrl();
                } else {
                    forwardUrl = "../jsp/fileNotAuthorized.jsp";
                }

                break;
            case ACTION_SEARCH_SUBJECT:
                String subjectLike = request.getParameter("nameSubject");
                subjects = SubjectManager.search(subjectLike);
                request.setAttribute("subjects", subjects);
                forwardUrl = "../jsp/printSearch.jsp";
                break;
        }

        return forwardUrl;
    }

    public static void returnFile(String filename, OutputStream out)
            throws FileNotFoundException, IOException {
        InputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(filename));
            byte[] buf = new byte[4 * 1024];  // 4K buffer
            int bytesRead;
            while ((bytesRead = in.read(buf)) != -1) {
                out.write(buf, 0, bytesRead);
            }
        } finally {
            if (in != null) in.close();
        }
    }

    public void copy(File src, File dst) {
        try {
            InputStream in = new FileInputStream(src);
            OutputStream out = new FileOutputStream(dst);

            // Transfer bytes from in to out
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
        } catch (IOException io) {
            System.err.println("Error al copiar el archivo");//remove serr
        }
    }

    private Map<String, String> getParams(List items) {

        Map<String, String> params = new HashMap<String, String>();

        for (int i = 0; i < items.size(); i++) {
            FileItem fileItem = (FileItem) items.get(i);
            if (fileItem.isFormField()) {
                params.put(fileItem.getFieldName(), fileItem.getString());
            }
        }

        return params;

    }

    private Map<String, FileItem> getFiles(List items) {

        Map<String, FileItem> params = new HashMap<String, FileItem>();

        for (int i = 0; i < items.size(); i++) {
            FileItem fileItem = (FileItem) items.get(i);
            if (!fileItem.isFormField()) {
                params.put(fileItem.getFieldName(), fileItem);
            }
        }

        return params;

    }

    private File uploadFile(FileItem fileItem) {
        // Metodo creado con mucha colaboracion de Nico y Pato
        File uploadFile = null;
        // Parse the request
        try {
            final File jspPath = new File(getServletContext().getRealPath("/jsp/index.jsp"));
            final File fileRepository = new File(jspPath.getParentFile().getParentFile(), "files");
            uploadFile = new File(fileRepository, fileItem.getName());

            FileOutputStream outputStream = null;
            InputStream inputStream = null;
            try {
                outputStream = new FileOutputStream(uploadFile);
                inputStream = fileItem.getInputStream();


                int nextInt = inputStream.read();

                while (nextInt != -1) {
                    outputStream.write(nextInt);
                    nextInt = inputStream.read();
                }

            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.flush();
                    outputStream.close();
                }
            }

        } catch (IOException e) {


        }

        return uploadFile;
    }
}*/